﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Models;

using Newtonsoft.Json;

namespace Server.Common
{
    public class DataHandle
    {
        #region 处理数据

        public RetModel HandlerData(byte[] data)
        {
            RetModel rm = new RetModel { Success = true };
            try
            {
                string jStr = Encoding.UTF8.GetString(data);
                Dictionary<string, object> dc = ResolveRecvDC(jStr);
                if (dc is null || dc?.Keys.Count < 1)
                    throw new Exception("无法识别的数据");
                string session = dc.Keys.Contains("sessionId") ? dc["sessionId"]?.ToString() : "";
                ProcessData(dc, ref rm);
            }
            catch (Exception ex)
            {
                rm.Success = false;
                rm.ErrCode = "9999";
                rm.ErrInfo = ex.Message;
                Comm.RaiseWriteText(ex.Message);
            }
            return rm;
        }

        private static Dictionary<string, object> ResolveRecvDC(string str)
        {
            return string.IsNullOrEmpty(str) ? new Dictionary<string, object>() : JsonConvert.DeserializeObject<Dictionary<string, object>>(str);
        }

        #endregion 处理数据

        #region 判断命令类型

        public void ProcessData(Dictionary<string, object> dc, ref RetModel rm)
        {
            if (!dc.Keys.Contains("cmd"))
                throw new Exception("数据不正确！");
            string reqId = dc.Keys.Contains("reqId") ? dc["reqId"]?.ToString() : "";
            Cmd cmd = (Cmd)Enum.Parse(typeof(Cmd), dc["cmd"].ToString());
            string session = dc.Keys.Contains("sessionId") ? dc["sessionId"]?.ToString() : "";
            if (cmd != Cmd.Usr_Login)
            {
                SessionModel sess = CheckUserLogin(session);
                dc["sess"] = sess;
            }
            rm = Comm.BLLHandle.Keys.Contains(cmd) ? Comm.BLLHandle[cmd].Invoke(dc) : new RetModel { Success = false };
            rm.ReqID = reqId;
        }

        #endregion 判断命令类型

        #region 检查用户登录情况

        private SessionModel CheckUserLogin(string uSession)
        {
            var online = Comm.GetOnlineInfo(uSession);
            if (null == online)
                throw new Exception("用户未登录！");
            online.UpdateTime = DateTime.Now;
            return online;
        }

        #endregion 检查用户登录情况
    }
}